package pro.spring.controller.frontController;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import pro.spring.model.Information;
import pro.spring.vo.PaginationVo;

@Controller("YunController")
@RequestMapping("/yun")
public class YunController extends BaseController{
	String local="page/front/come/";
	@RequestMapping(value="moreinfo",method=RequestMethod.GET)
	public String list(@RequestParam(value = "p", defaultValue = "1")Integer pagenum,Integer offset,ModelMap map){
		if(offset==null){
			offset=1;
		}
		PaginationVo<Information> allfile=yunService.getPaginationInfo(pagenum,10);
		map.put("all",allfile);
		map.put("type", "文件列表");
		return local+"moreinfo";
	}
	@RequestMapping("/upload")
	public String upload(){
		return local+"upload";
	}
	
	@RequestMapping(value="doupload.html",method=RequestMethod.POST)
	public String doUpload(@RequestParam("file")CommonsMultipartFile file,Information information,HttpServletRequest req) throws Exception{
		//type=yunService.upload(file);
		//return type+"";
		HttpSession session=req.getSession();
		Integer usersUId = (Integer)session.getAttribute("uId");
		information.setUsersUId(usersUId);
		yunService.upload(file,information);
		return "redirect:../index/index.html";
	}
	
	
	@RequestMapping(value="download.html")
	public void downLoad(HttpServletRequest req,HttpServletResponse response,Integer inId) throws Exception{
		
			long size=0;
			Information information = yunService.getRealInfo(inId);
			size= yunService.getSize(inId);
			//InputStream in=yunService.download(information.getInLocalhost());
			//InputStream in =obj.getContent();
			InputStream in = yunService.download(inId);
	//		if(in!=null){
				String filename=URLEncoder.encode( information.getInTitle(), "UTF-8");
				response.reset();
				response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
				response.addHeader("Content-Length", "" + size); 
			    response.setContentType("applic ation/octet-stream;charset=UTF-8"); 
			    OutputStream out = new BufferedOutputStream(response.getOutputStream());
				int c;
				while((c=in.read())!=-1 ){ 
					out.write(c);
					out.flush();
				}
				out.flush();
				out.close();
	//		}else{
	//			System.out.println("InputStream --------"+in);
	//			
	//		}
		
	}
	
}